/**
 * Created by Administrator on 2017/4/25.
 */
require('./uuid.js');
var utilMD5 = require('./MD5.js');
var moment = require("moment");
var co = require('co');

Date.prototype.format = function (format) {
    var o = {
        "M+": this.getMonth() + 1, //month
        "d+": this.getDate(), //day
        "h+": this.getHours(), //hour
        "m+": this.getMinutes(), //minute
        "s+": this.getSeconds(), //second
        "q+": Math.floor((this.getMonth() + 3) / 3), //quarter
        "S": this.getMilliseconds() //millisecond
    }

    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }

    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
}

function toMoment(timeStamp) {
    return moment(timeStamp * 1000);
}
var util = {
    getUUID: function () {
        return Math.uuid();
    },
    getDayByWeek: function (day) {
        var myDate = new Date(); //获取今天日期
        myDate.setDate(myDate.getDate() - day);
        return myDate.format("yyyy-MM-dd");
    },
    /**
     * 获取当前时间戳
     */
    getNowTimeStamp: function () {
        return moment().unix();
    },
    /**
     * 获取当前时间-YYYY-MM-DD HH:mm:ss
     */
    getNowTime: function () {
        return moment().format("YYYY-MM-DD HH:mm:ss");
    },
    getNowDate: function () {
        return moment().format("YYYY-MM-DD");
    },
    getNowTimeString: function () {
        return moment().format("YYYYMMDDHHmmss");
    },
    toDateTimeString: function (timeStamp) {
        return toMoment(timeStamp).format('YYYY-MM-DD HH:mm:ss');
    },
    toDateString: function (timeStamp) {
        return toMoment(timeStamp).format('YYYY-MM-DD');
    },
    toTimeString: function (timeStamp) {
        return toMoment(timeStamp).format('HH:mm:ss');
    },
    MD5: function (str) {
        return utilMD5.MD5(str);
    },
    getFirstDay: function () {
        var firstDay = moment().day(1).format('YYYY-MM-DD');
        return firstDay + " 00:00:00";
    },
    getLastDay: function () {
        var lastDay = moment().day(7).format('YYYY-MM-DD');
        return lastDay + " 23:59:59";
    },
    getIP: function () {
        return "http://192.168.1.10:3000/";
    },
    valPhone: function (phone) {
        var isPhone = /^1[3|4|5|7|8][0-9]{9}$/;
        // var isPhone=/^(?:13\d|15\d|18\d)\d{8}$/;
        return isPhone.test(phone);
    },
    checkEmail: function (str) {
        var re = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})|(\w-*\.*)+@(\w-?)+(\.\w{2,})+(\.\w{2,})+$/
        if (re.test(str)) {
            return true;
        } else {
            return false;
        }
    }
}
module.exports = util;